import bfproto from './bf-proto'
import {state} from './bf-store'
import bfevent from '../utils/bf-event'
import bfconsole from '../utils/bf-console'
import bfstore from './bf-store'
import bfDbcmd from '../modules/proto/internet_radio_db.cmd'
import bfelem from './bf-element'
import bfi18n from './bf-i18n'

export default {
    protoSeqNo: 0,
    connectCount: 0,
    getProtoSeqNo() {
        ++this.protoSeqNo;
        if (this.protoSeqNo > 200000000) {
            this.protoSeqNo = 0;
        }
        return this.protoSeqNo
    },
    protoRpcId: 0,
    getProtoRpcId() {
        ++this.protoRpcId;
        if (this.protoRpcId > 200000000) {
            this.protoRpcId = 0;
        }
        return this.protoRpcId
    },
    //根据消息名生成的类型对象
    getProtoMessageType(msg_name) {
        var proto_name = "bfproto." + msg_name;
        var Tmsg = bfproto.lookup(proto_name);
        return Tmsg
    },
    Trpc_cmd() {
        return this.getProtoMessageType("rpc_cmd")
    },
    //new one rpc_cmd object
    newRpcCmd() {
        var rpc_cmd_obj = this.Trpc_cmd().create();
        rpc_cmd_obj.rpcId = this.getProtoRpcId();
        rpc_cmd_obj.seqNo = this.getProtoSeqNo();
        rpc_cmd_obj.sysId = state.systemInfo.sysId;
        rpc_cmd_obj.sid = state.ssid;
        return rpc_cmd_obj;
    },
    // 向服务器发送webSocket数据
    msgObserver: {},
    sendMessage(rpc_cmd_obj, timeout = 60) {
        return new Promise((resolve, reject) => {
            try {
                // 编码 rpc_cmd 命令数据
                let rpc_cmd_t = this.Trpc_cmd();
                let rpc_cmd_bytes = rpc_cmd_t.encode(rpc_cmd_obj).finish();

                // 发送命令超时机制
                let replyTo = rpc_cmd_obj.rpcId;
                let __replyTo = rpc_cmd_obj.cmd + "@" + rpc_cmd_obj.rpcId;
                // 监听服务器响应成功后，返回数据并解绑监听此命令事件
                let __resFunc = (_rpc_cmd_obj) => {
                    resolve(_rpc_cmd_obj);
                };
                bfevent.once(__replyTo, __resFunc);

                if (typeof timeout !== 'number') {
                    timeout = 60;
                }
                this.msgObserver[replyTo] = setTimeout(() => {
                    if (!this.msgObserver[replyTo]) {
                        return
                    }
                    delete this.msgObserver[replyTo];

                    // 超时后解绑rpcId的自定义事件，避免出现rpcId循环重复的耦合bug
                    bfevent.off(__replyTo, __resFunc);
                    reject(replyTo);
                    bfelem.messageBox(bfi18n.t("notify.resTimeout"), "warning");
                }, timeout * 1000);

                // 发送数据到服务器
                if (!state.socket || state.socket.readyState !== 1) {
                    reject("webSocket is not opened!");
                    return false;
                }
                // 心跳链接
                this.keepWebSocketConnect();
                state.socket.send(rpc_cmd_bytes);
            } catch (err) {
                reject(err);
            }
        });
    },
    // 解码rpc_cmd命令数据
    decodeRpcMsg(msgType, bufferArray) {
        let rpcMsgType = this.getProtoMessageType(msgType);

        try {
            return rpcMsgType.decode(new Uint8Array(bufferArray));
        } catch (err) {
            bfconsole.error("decodeRpcMsg:", err);
            return {}
        }
    },
    // 服务器向web前端发送的消息都在这个方法中解析
    resolveSocketMessage(data) {
        //websocket直接传输二进制，不需要进行二进制字符串转换
        let rpc_cmd_obj = this.decodeRpcMsg("rpc_cmd", data);
        // bfconsole.log("%c resolveSocketMessage:", "font-size:20px;color:#20a0ff", rpc_cmd_obj);

        // 清除超时回调
        clearTimeout(this.msgObserver[rpc_cmd_obj.rpcId]);
        delete this.msgObserver[rpc_cmd_obj.rpcId];

        if (rpc_cmd_obj.cmd == 0) {
            // webSocket 连接成功后，服务器响应的服务器信息
            let body = this.decodeRpcMsg("server_info", rpc_cmd_obj.body);
            bfstore.commit("saveServerInfo", body);
            bfevent.emit("serverConnected");
        }
        if (rpc_cmd_obj.cmd == 21) {
            // 发生错误，错误内容见res_info
            bfconsole.error("rpc_cmd 21 cmd error:", rpc_cmd_obj.resInfo);
        }

        // 发布一个 cmd+@+rpcId 消息事件，各组件订阅该命令事件及响应
        let subject = rpc_cmd_obj.cmd + "@" + rpc_cmd_obj.rpcId;
        bfevent.emit(subject, rpc_cmd_obj);
    },
    // 向服务器请求数据库表rid
    requestRids(ridType = 2, ridCount = 3) {
        let rpc_cmd_obj = this.newRpcCmd();
        let client_rid_request_t = this.getProtoMessageType("client_rid_request");
        let msgObj = {
            ridType,
            ridCount
        };
        // 通过 verify 验证消息字段类型
        let errMsg = client_rid_request_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let client_rid_request_obj = client_rid_request_t.create(msgObj);

        rpc_cmd_obj.cmd = 8;
        rpc_cmd_obj.body = client_rid_request_t.encode(client_rid_request_obj).finish();

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            // 解析出服务器响应的数据，并将结果保存至 this.$store.state.rids 中
            let body = this.decodeRpcMsg("client_rid_response", res.body);
            bfconsole.log("requestRids res:", body);
            bfstore.commit("saveRids", [...state.rids, ...body.rids]);
        }).catch(err => {
            bfconsole.error("requestRids fail:", err)
        })
    },
    // todo 向服务器请求数据库表dmrId
    requestDmrIds(ridType = 2, ridCount = 3) {
        let dmrIds = [];
        for (let i = 0; i < ridCount; i++) {
            let bit_1 = (new Date().getTime() / 1000).toString(16).substr(-2);
            let bit_2 = Math.random().toString(16).substr(-2);
            let bit_3 = Math.random().toString(16).substr(-2);
            let dmrId = "00" + bit_1 + bit_2 + bit_3;
            dmrId = dmrId.toUpperCase();
            dmrIds.push(dmrId);
        }
        bfstore.commit("saveDmrIds", [...state.dmrIds, ...dmrIds]);
        bfconsole.log("requestDmrIds res:", dmrIds);

        // let rpc_cmd_obj = this.newRpcCmd();
        // let client_rid_request_t = this.getProtoMessageType("client_rid_request");
        // let msgObj = {
        //     ridType,
        //     ridCount
        // };
        // // 通过 verify 验证消息字段类型
        // let errMsg = client_rid_request_t.verify(msgObj);
        // if (errMsg) {
        //     bfconsole.error(errMsg);
        //     return;
        // }
        // let client_rid_request_obj = client_rid_request_t.create(msgObj);
        //
        // rpc_cmd_obj.cmd = 8;
        // rpc_cmd_obj.body = client_rid_request_t.encode(client_rid_request_obj).finish();
        //
        // this.sendMessage(rpc_cmd_obj, 30).then(res => {
        //     bfconsole.log("requestDmrIds res:", res);
        //     // 解析出服务器响应的数据，并将结果保存至 this.$store.state.dmrIds 中
        //     let body = this.decodeRpcMsg("client_rid_response", res.body);
        //     this.$store.commit("saveDmrIds", [...state.dmrIds, ...body.rids]);
        // }).catch(err => {
        //     bfconsole.error("requestDmrIds fail:", err);
        // })
    },
    // 设置操作表信息
    setDbOptionMsg(opts) {
        let db_option_t = this.getProtoMessageType('db_option');
        let db_option_obj = db_option_t.create(opts);

        return db_option_t.encode(db_option_obj).finish();
    },
    newWebsocketConnect() {
        let location = window.location;
        let ws_addr = "";
        ws_addr += location.hostname;
        ws_addr += ":";
        if (location.hostname == 'localhost') {
            // 开发环境
            ws_addr += 8200;
            ws_addr = `ws://${ws_addr}/socket`
        } else {
            // 生产部署环境
            let port = location.port;
            if (location.protocol == "https") {
                port = port || 443;
                ws_addr += port;
                ws_addr = `wss://${ws_addr}/socket`
            } else {
                port = port || 80;
                ws_addr += port;
                ws_addr = `ws://${ws_addr}/socket`
            }
        }
        let ws = new WebSocket(ws_addr);
        ws.binaryType = 'arraybuffer';
        ws.onopen = () => {
            bfstore.commit("setSocket", ws);
        };
        ws.onmessage = (evt) => {
            if (evt.data != null) {
                let res = new Uint8Array(evt.data);
                this.resolveSocketMessage(res);
            } else {
                ws.close();
            }
        };
        ws.onclose = () => {
            bfevent.emit("diconnect");
            // 默认每3秒重连一次服务器，上限20次
            if (this.connectCount < 20) {
                setTimeout(() => {
                    this.connectCount++;
                    bfconsole.warn("socket connect count:", this.connectCount);
                    this.newWebsocketConnect();
                }, 3000)
            }
        };
    },
    // 与服务器保持连接的命令,pingTimeout为ping定时器实例
    heartBeatCount: 0,
    pingInterval: null,
    keepWebSocketConnect() {
        clearTimeout(this.pingInterval);
        this.pingInterval = setInterval(() => {
            let rpc_cmd_obj = this.newRpcCmd();
            let ping_t = this.getProtoMessageType("ping");
            let msgObj = {
                pingCode: this.heartBeatCount % 10 ? 1 : 2,
                pong: 1,
            };
            // 通过 verify 验证消息字段类型
            let errMsg = ping_t.verify(msgObj);
            if (errMsg) {
                bfconsole.error(errMsg);
                return;
            }
            let ping_obj = ping_t.create(msgObj);

            rpc_cmd_obj.cmd = 20;
            rpc_cmd_obj.body = ping_t.encode(ping_obj).finish();

            this.sendMessage(rpc_cmd_obj, 30).then(res => {
                this.heartBeatCount++;
                bfconsole.log("keepWebSocketConnect res:", this.heartBeatCount);
                let body = this.decodeRpcMsg("ping", res.body);
                if (body.serverTime != 0) {
                    bfstore.commit("saveServerTime", body.serverTime);
                }
            }).catch(err => {
                bfconsole.error("keepWebSocketConnect fail:", err);
            })
        }, 270 * 1000);

    },
    // 请求图片资源
    commitImgItem(db_org) {
        let payload = {
            key: db_org.rid,
            val: db_org,
            index: db_org.hash
        };
        bfstore.commit("setImgItem", payload);
    },
    requestImagesByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_image_t = this.getProtoMessageType("db_image");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_image_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_image_obj = db_image_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_image,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_image_t.encode(db_image_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_image_list", res.body);
            bfconsole.log("requestImagesByParentId data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let item = body.rows[i];
                this.commitImgItem(item);
            }
        }).catch(err => {
            bfconsole.error("requestImagesByParentId fail:", err);
        })
    },
    // 请求组织的下属组织数据
    requestOrganizationByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_org_t = this.getProtoMessageType("db_org");
        let msgObj = {
            parentId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_org_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_org_obj = db_org_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_org,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["parent_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_org_t.encode(db_org_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_org_list", res.body);
            bfconsole.log("requestOrganizationByParentId data:", body);
            if (body.rows.length == 0) {
                // 没有组织数据
                // bfelem.warningBox("没有任何组织数据的权限");
                // bfconsole.error("can not found the user has permission org");
                return
            }
            for (let i = 0; i < body.rows.length; i++) {
                let orgData = body.rows[i];
                // 将数据保存到state
                this.commitOrgItem(orgData);

                // 递归获取下级数据
                this.requestOrganizationByParentId(orgData);
            }
        }).catch(err => {
            bfconsole.error("requestOrganizationByParentId fail:", err);
        })
    },
    // 通过rid请求组织数据
    commitOrgItem(db_org) {
        db_org.orgType = db_org.orgType || 0;
        let payload = {
            key: db_org.rid,
            val: db_org,
            index: db_org.selfId,
            selectOpts: {
                rid: db_org.rid,
                label: db_org.shortName
            }
        };
        bfstore.commit("setOrgItem", payload);
    },
    requestOrganizationByRid(userPermData, hasChild = 0) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_org_t = this.getProtoMessageType("db_org");
        let msgObj = {
            rid: userPermData.userOrg
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_org_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_org_obj = db_org_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_org,
            operationNo: bfDbcmd.OpGetOneByRid
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_org_t.encode(db_org_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let orgData = this.decodeRpcMsg("db_org", res.body);
            bfconsole.log("requestOrganizationByRid data:", orgData);
            // 将数据保存到state
            this.commitOrgItem(orgData);

            // todo 获取下级组织数据，得到的下级组织数据中，需要判断是否有独立的权限，并根据权限处理逻辑
            // if (hasChild !== 1) {
            //     return
            // }
            // 如果用户拥有该组织的下级权限，则通过parentId获取下级组织数据
            // if (userPermData.userPerm > 8) {
            // 查找下级组织数据
            // this.requestOrganizationByParentId(orgData);
            // }
            this.requestImagesByParentId(orgData);
            this.requestOrganizationByParentId(orgData);
            this.requestUsersByParentId(orgData);
            this.requestDevicesByParentId(orgData);
            this.requestGroupByParentId(orgData);
            this.requestShareGroupByParentId(orgData);
            this.requestDeviceSettingByParentId(orgData);
        }).catch(err => {
            bfconsole.error("requestOrganizationByRid fail:", err);
        })
    },
    // todo 请求有权限的组织数据
    requestOrganization() {
        let rpc_cmd_obj = this.newRpcCmd();
        rpc_cmd_obj.cmd = 1000;
        rpc_cmd_obj.paraStr = state.userInfo.originData.rid.toString();

        this.sendMessage(rpc_cmd_obj, 300).then(res => {
            let orgData = this.decodeRpcMsg("db_org_list", res.body);
            if (res.cmdInfo === 22) {
                // 有错误信息
                bfconsole.error(res.resInfo);
                return
            }
            bfconsole.log("request permission res:", res, orgData);
            for (let key in orgData.rows) {
                let org = orgData.rows[key];
                // 获取组织下的其他类型数据
                this.requestImagesByParentId(org);
                this.requestUsersByParentId(org);
                this.requestDevicesByParentId(org);
                this.requestGroupByParentId(org);
                this.requestShareGroupByParentId(org);
                this.requestDeviceSettingByParentId(org);

                this.commitOrgItem(org);
            }
            console.log(1111111111)
            bfevent.once("treeLoad", () => {
                console.log(333333333)
                bfevent.emit("getAllData");
            })
        }).catch(err => {
            bfconsole.error("requestOrganization fail:", err);
        })
    },
    // 保存权限表数据
    commitUserPermItem(userRid, rows) {
        let userPermObj = {};
        for (let k = 0; k < rows.length; k++) {
            let item = rows[k];
            userPermObj[item.userOrg] = item;
        }
        let payload = {
            key: userRid,
            val: userPermObj
        };
        bfstore.commit("setUserPermItem", payload);
    },
    requestUserPermissionOrg(userRid, callback) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_user_permission_t = this.getProtoMessageType("db_user_permission");
        let msgObj = {
            userRid: userRid || state.userInfo.originData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_user_permission_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_user_permission_obj = db_user_permission_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_user_permission,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["user_rid"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_user_permission_t.encode(db_user_permission_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_user_permission_list", res.body);
            bfconsole.log("request permission res:", body);
            this.commitUserPermItem(db_user_permission_obj.userRid, body.rows);
            if (callback === 1) {
                return
            }
            if (typeof callback === 'function') {
                callback(body);
                return
            }

            for (let k = 0; k < body.rows.length; k++) {
                let item = body.rows[k];
                // 通过权限表的组织rid获取组织数据
                this.requestOrganizationByRid(item);
            }
            // todo 模拟已经请求完所有数据，开始加载列表树节点
            setTimeout(() => {
                bfevent.emit("getAllData");
            }, 3000);
        }).catch(err => {
            bfconsole.error("request permission fail:", err);
        })
    },
    // todo 请求组织下的设备数据
    commitDeviceItem(db_device) {
        db_device.dmrId = db_device.dmrId.toString(16).toUpperCase().padStart(8, "0");
        db_device.deviceType = db_device.deviceType || 0;
        db_device.priority = db_device.priority || 0;
        db_device.deviceUser = db_device.deviceUser || 0;
        db_device.isPttDisabled = db_device.isPttDisabled || 0;
        db_device.isSpeakerDisabled = db_device.isSpeakerDisabled || 0;
        db_device.isLocked = db_device.isLocked || 0;
        let payload = {
            key: db_device.rid,
            val: db_device,
            index: db_device.dmrId,
            selectOpts: {
                rid: db_device.rid,
                label: db_device.name,
                dmrId: db_device.dmrId
            }
        };
        bfstore.commit("setDeviceItem", payload);
    },
    requestDevicesByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_device_t = this.getProtoMessageType("db_device");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_device_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_device_obj = db_device_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_device,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_device_t.encode(db_device_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_device_list", res.body);
            bfconsole.log("requestDevicesByParentId data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let device = body.rows[i];
                // 将数据保存到state
                this.commitDeviceItem(device);
            }
        }).catch(err => {
            bfconsole.error("requestDevicesByParentId fail:", err);
        })
    },
    // todo 请求组织下的用户数据
    commitUserItem(db_user) {
        let payload = {
            key: db_user.rid,
            val: db_user,
            index: db_user.rfid,
            selectOpts: {
                rid: db_user.rid,
                label: db_user.name,
                rfid: db_user.rfid
            }
        };
        bfstore.commit("setUserItem", payload);
    },
    requestUsersByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_user_t = this.getProtoMessageType("db_user");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_user_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_user_obj = db_user_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_user,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_user_t.encode(db_user_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_user_list", res.body);
            bfconsole.log("requestUsersByParentId data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let user = body.rows[i];
                this.commitUserItem(user);
            }
        }).catch(err => {
            bfconsole.error("requestUsersByParentId fail:", err);
        })
    },

    commitGroupItem(db_radio_group) {
        db_radio_group.dmrId = db_radio_group.dmrId.toString(16).toUpperCase().padStart(8, "0");
        let payload = {
            key: db_radio_group.rid,
            val: db_radio_group,
            index: db_radio_group.dmrId,
            selectOpts: {
                rid: db_radio_group.rid,
                label: db_radio_group.name,
                dmrId: db_radio_group.dmrId
            }
        };
        bfstore.commit("setGroupItem", payload);
    },
    requestGroupByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_group_t = this.getProtoMessageType("db_radio_group");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_group_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_group_obj = db_group_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_radio_group,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_group_t.encode(db_group_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_radio_group_list", res.body);
            bfconsole.log("requestGroupByParentId data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let group = body.rows[i];
                this.commitGroupItem(group);
            }
        }).catch(err => {
            bfconsole.error("requestGroupByParentId fail:", err);
        })
    },

    commitShareGroupItem(db_share_group) {
        db_share_group.dmrId = db_share_group.dmrId.toString(16).toUpperCase().padStart(8, "0");
        let payload = {
            key: db_share_group.rid,
            val: db_share_group,
            index: db_share_group.dmrId,
            selectOpts: {
                rid: db_share_group.rid,
                label: db_share_group.dmrId,
                dmrId: db_share_group.dmrId
            }
        };
        bfstore.commit("setShareGroupItem", payload);
    },
    requestShareGroupByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_share_group_t = this.getProtoMessageType("db_share_group");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_share_group_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_share_group_obj = db_share_group_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_share_group,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_share_group_t.encode(db_share_group_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_share_group_list", res.body);
            bfconsole.log("requestShareGroupByParentId data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let group = body.rows[i];
                this.requestGroupByDmrid(group);
            }
        }).catch(err => {
            bfconsole.error("requestShareGroupByParentId fail:", err);
        })
    },
    // todo 请求组织下的设备信道配置数据
    commitDeviceSettingItem(deviceSetting) {
        let payload = {
            key: deviceSetting.rid,
            val: deviceSetting
        };
        bfstore.commit("setDeviceSettingItem", payload);
    },
    requestDeviceSettingByParentId(parentData) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_share_group_t = this.getProtoMessageType("db_device_setting");
        let msgObj = {
            orgId: parentData.rid
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_share_group_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_share_group_obj = db_share_group_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_device_setting,
            operationNo: bfDbcmd.OpGetListByCustom,
            conditionColumns: ["org_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_share_group_t.encode(db_share_group_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_device_setting_list", res.body);
            bfconsole.log("db_device_setting data:", body);
            for (let i = 0; i < body.rows.length; i++) {
                let group = body.rows[i];
                this.commitDeviceSettingItem(group);
            }
        }).catch(err => {
            bfconsole.error("db_device_setting fail:", err);
        })
    },
    requestGroupByDmrid (group) {
        let rpc_cmd_obj = this.newRpcCmd();
        let db_group_t = this.getProtoMessageType("db_radio_group");
        let msgObj = {
            dmrId: group.dmrId
        };
        // 通过 verify 验证消息字段类型
        let errMsg = db_group_t.verify(msgObj);
        if (errMsg) {
            bfconsole.error(errMsg);
            return;
        }
        let db_group_obj = db_group_t.create(msgObj);

        let db_opts = {
            tableNo: bfDbcmd.db_radio_group,
            operationNo: bfDbcmd.OpGetOneByCustom,
            conditionColumns: ["dmr_id"]
        };

        rpc_cmd_obj.cmd = 10;
        rpc_cmd_obj.body = db_group_t.encode(db_group_obj).finish();
        rpc_cmd_obj.paraBin = this.setDbOptionMsg(db_opts);

        this.sendMessage(rpc_cmd_obj, 30).then(res => {
            let body = this.decodeRpcMsg("db_radio_group", res.body);
            bfconsole.log("requestGroupBydmrId data:", body);
            group.selfId =body.selfId;
            group.oriOrgId = body.orgId;
            group.name = body.name;
            this.commitShareGroupItem(group);
        }).catch(err => {
            bfconsole.error("requestGroupBydmrId fail:", err);
        })
    }
}

